package com.sskj.xgja.market;


import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sskj.base.Constant;
import com.sskj.base.socket.MarketWebSocket;
import com.sskj.base.socket.WebSocketObserver;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.GsonUtil;
import com.sskj.base.view.ToolBarLayout;
import com.sskj.xgja.MVPActivity;
import com.sskj.xgja.R;
import com.sskj.xgja.main.MainActivity;
import com.sskj.xgja.market.bean.MarketData;
import com.sskj.xgja.market.bean.SocketMarket;
import com.sskj.xgja.market.bean.Stock;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import razerdp.basepopup.BasePopupWindow;

/**
 * @author Hey
 * Create at  2019/03/21
 */
public class MarketDetailActivity extends MVPActivity<MarketDetailPresenter> {
    @BindView(R.id.priceNow)
    TextView mPriceNow;
    @BindView(R.id.changeRate)
    TextView mChangeRate;
    @BindView(R.id.highText)
    TextView mHighText;
    @BindView(R.id.highPrice)
    TextView mHighPrice;
    @BindView(R.id.lowText)
    TextView mLowText;
    @BindView(R.id.lowPrice)
    TextView mLowPrice;
    @BindView(R.id.changeMark)
    TextView changeMark;
    @BindView(R.id.market_info)
    RelativeLayout mMarketInfo;
    @BindView(R.id.marketFrame)
    FrameLayout mMarketFrame;
    @BindView(R.id.marketTab)
    TabLayout marketTab;
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.marketcCnyPrice)
    TextView marketCnyPrice;  // 人民币价钱
    @BindView(R.id.marketBuy)
    TextView mMarketBuy;
    @BindView(R.id.marketSale)
    TextView mMarketSale;

    private ChangeMarkPopupWindow changeMarkPopupWindow;

    private boolean isUpToggle;
    private boolean isDownToggle;
    //K线相关
    private int currentIndex = 0;
    private String[] goodsType = {"minute", "minute30", "minute60", "minute120", "day"};
    private ArrayList<ChartFragment> fragmentList = new ArrayList<>();

    private MarketData code;

    private MarketWebSocket webSocket;

    @Override
    public int getLayoutId() {
        return R.layout.activity_market_detail;
    }

    @Override
    public MarketDetailPresenter getPresenter() {
        return new MarketDetailPresenter();
    }

    @Override
    public void initView() {
        code = (MarketData) getIntent().getSerializableExtra("code");
        toolbar.setTitle(code.getName());
        toolbar.setLeftButtonOnClickListener(v -> finish());
        initTab();
        //隐藏币币交易按钮
        mMarketBuy.setVisibility(View.VISIBLE);
        changeMark.setOnClickListener(v -> {
            if (changeMarkPopupWindow == null) {
                changeMarkPopupWindow = new ChangeMarkPopupWindow(this);
                View contentView = changeMarkPopupWindow.getContentView();
                TextView tvMa = contentView.findViewById(R.id.tvMa);
                TextView tvBoll = contentView.findViewById(R.id.tvBoll);
                TextView tvMacd = contentView.findViewById(R.id.tvMacd);
                TextView tvKdj = contentView.findViewById(R.id.tvKdj);
                TextView tvRsi = contentView.findViewById(R.id.tvRsi);
                TextView tvWr = contentView.findViewById(R.id.tvWr);
                ImageView ivUpToggle = contentView.findViewById(R.id.ivUpToggle);
                ImageView ivDownToggle = contentView.findViewById(R.id.ivDownToggle);
                tvMa.setOnClickListener(view -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    ivUpToggle.setImageResource(R.mipmap.icon_wenhao);
                    changeMarkPopupWindow.dismiss();
                });

                tvBoll.setOnClickListener(v1 -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawBollShow();
                    ivUpToggle.setImageResource(R.mipmap.icon_wenhao);
                    changeMarkPopupWindow.dismiss();
                });

                ivDownToggle.setOnClickListener(v1 -> {
                    if (isUpToggle) {
                        isUpToggle = false;
                        ivUpToggle.setImageResource(R.mipmap.icon_right_arrows);

                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawNoneShow();
                    } else {
                        isUpToggle = true;
                        ivUpToggle.setImageResource(R.mipmap.icon_wenhao);
                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setMainDrawMaShow();
                    }
                    changeMarkPopupWindow.dismiss();
                });

                tvMacd.setOnClickListener(v1 -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeMACD();
                    changeMarkPopupWindow.dismiss();
                });
                tvKdj.setOnClickListener(v1 -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeKDJ();
                    changeMarkPopupWindow.dismiss();
                });
                tvRsi.setOnClickListener(v1 -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeRSI();
                    changeMarkPopupWindow.dismiss();
                });

                tvWr.setOnClickListener(v1 -> {
                    fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().changeWR();
                    changeMarkPopupWindow.dismiss();
                });

                ClickUtil.click(ivDownToggle, view -> {
                    if (isDownToggle) {
                        isDownToggle = false;
                        ivDownToggle.setImageResource(R.mipmap.icon_right_arrows);
                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    } else {
                        isDownToggle = true;
                        ivDownToggle.setImageResource(R.mipmap.icon_wenhao);

                        fragmentList.get(marketTab.getSelectedTabPosition()).getKChartView().setDrawDown(isDownToggle);
                    }
                    changeMarkPopupWindow.dismiss();

                });
                changeMarkPopupWindow.showPopupWindow(marketTab);
            } else {
                if (changeMarkPopupWindow.isShowing()) {
                    changeMarkPopupWindow.dismiss();
                } else {
                    changeMarkPopupWindow.showPopupWindow(marketTab);
                }
            }
        });

    }

    @Override
    public void initData() {
        if (parseFloat(code.getChange()) > 0) {
            mChangeRate.setTextColor(getResources().getColor(R.color.red));
            mChangeRate.setText("+" + code.getChangeRate());
            mPriceNow.setTextColor(getResources().getColor(R.color.red));
        } else {
            mChangeRate.setTextColor(getResources().getColor(R.color.green));
            mChangeRate.setText(code.getChangeRate());
            mPriceNow.setTextColor(getResources().getColor(R.color.green));
        }
        mHighPrice.setText(code.getHigh() + "");
        mLowPrice.setText(code.getLow() + "");
        mPriceNow.setText(code.getPrice() + "");

        ClickUtil.click(mMarketBuy, view -> MainActivity.startToIndex(this, 2, 0, code));
        ClickUtil.click(mMarketSale, view -> MainActivity.startToIndex(this, 2, 1, code));


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webSocket != null) {
            webSocket.closeWebSocket();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        openWebSocket();
    }


    public void openWebSocket() {
        JSONObject message = new JSONObject();
        try {
            message.put("code", "all");
            webSocket = new MarketWebSocket(Constant.MARKET_WS, "detail", message.toString());
            webSocket.observer("detail", new WebSocketObserver() {
                @Override
                public void onNext(String s) {
                    SocketMarket data = GsonUtil.GsonToBean(s, SocketMarket.class);
                    updateView(data);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void updateView(SocketMarket stock) {
        if (stock == null) {
            return;
        }
        runOnUiThread(() -> {
            if (stock.getCode().equals(code.getCode())) {
                if (stock.getChange() > 0) {
                    mChangeRate.setTextColor(getResources().getColor(R.color.red));
                    mChangeRate.setText("+" + stock.getChangeRate());
                    mPriceNow.setTextColor(getResources().getColor(R.color.red));
                } else {
                    mChangeRate.setTextColor(getResources().getColor(R.color.green));
                    mChangeRate.setText(stock.getChangeRate());
                    mPriceNow.setTextColor(getResources().getColor(R.color.green));
                }
                mHighPrice.setText(stock.getHigh() + "");
                mLowPrice.setText(stock.getLow() + "");
                mPriceNow.setText(stock.getPrice() + "");
                //更新分时线
                if (fragmentList.get(currentIndex) != null) {
                    fragmentList.get(currentIndex).socketPrice = stock.getPrice() + "";
                    fragmentList.get(currentIndex).upDate(copyStock(stock));
                }

            }
        });
    }


    public Stock copyStock(SocketMarket newStock) {
        Stock stock = new Stock();
        stock.setCode(newStock.getCode());
        stock.setOpenPrice(newStock.getOpenPrice());
        stock.setClosePrice(newStock.getPrice());
        stock.setHigh(newStock.getHigh());
        stock.setLow(newStock.getLow());
        stock.setVolume(newStock.getVolume());
        stock.setTimestamp(newStock.getTimestamp());
        return stock;
    }


    public Float parseFloat(String s) {
        Float result;
        if (TextUtils.isEmpty(s)) {
            return 0f;
        }
        try {
            result = Float.parseFloat(s);
        } catch (Exception e) {
            return 0f;
        }
        return result;
    }


    private void initTab() {
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        marketTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        selectTab(0);
    }

    /**
     * k线切换
     *
     * @param index
     */
    private void selectTab(int index) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ChartFragment minuteFragment = fragmentList.get(index);
        ChartFragment currentFragment = fragmentList.get(currentIndex);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        if (minuteFragment == null) {
            if (index == 0) {
                minuteFragment = ChartFragment.newInstance(code.getCode(), goodsType[index], true);
            } else {
                minuteFragment = ChartFragment.newInstance(code.getCode(), goodsType[index], false);
            }
            fragmentList.set(index, minuteFragment);
            ft.add(R.id.marketFrame, minuteFragment);
        } else {
            ft.show(minuteFragment);
        }
        ft.commit();
        currentIndex = index;
    }

    public static void start(Context context, MarketData code) {
        Intent intent = new Intent(context, MarketDetailActivity.class);
        intent.putExtra("code", code);
        context.startActivity(intent);
    }

    private class ChangeMarkPopupWindow extends BasePopupWindow {

        public ChangeMarkPopupWindow(Context context) {
            super(context);
        }

        @Override
        public View onCreateContentView() {
            return LayoutInflater.from(getContext()).inflate(R.layout.change_mark, null);
        }
    }

}
